﻿using Microsoft.EntityFrameworkCore;
using StudentBackendService.Exceptions;
using StudentBackendService.Mappers;
using StudentBackendService.ViewObjects.Req;
using StudentBackendService.ViewObjects.Res;
using StudentManagerService.Models;

namespace StudentBackendService.Services.v1
{
    public class StudentManage : IStudentManage
    {
        private readonly SchoolContext _context;
        private readonly ILogger<StudentManage> _logger;

        public StudentManage(SchoolContext context, ILogger<StudentManage> logger)
        {
            _context = context;
            _logger = logger;
        }

        public Student AddOne(Student student)
        {
            if (_context.Students is null)
                throw new LogicException($"传入了一个空的学生数据", 400);
            student.IsDeleted = 0; // false - 表示未被删除
            student.CreateTime = DateTime.Now;
            student.Creator = "root";
            student.CreatorId = 0;
            _context.Students.Add(student);
            _context.SaveChanges();
            return student;
        }

        public Student GetById(long id)
        {
            var stu = _context.Students.AsNoTracking().SingleOrDefault(s => s.Id == id && s.IsDeleted == 0);
            return stu is null ? throw new LogicException($"{id} 对应的学生数据未找到", 404) : stu;
        }

        public WithPage<Student> List(StudentListReq req)
        {
            if (req is null)
                throw new LogicException($"查询条件为空", 400);
            var sql = _context.Students.Where(s => (req.Email == null || s.Email.Contains(req.Email))
            && (req.Name == null || s.Name.Contains(req.Name)))
                .OrderBy(s => s.Id)
                .Skip(req.Count())
                .Take(req.Size)
                .AsNoTracking();
            return new WithPage<Student>
            {
                List = sql.ToList(),
                Total = sql.Count()
            };
        }
    }
}
